package com.yilin.platform.base_core.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yilin.platform.base_core.application.UserUtil;
import com.yilin.platform.base_core.application.ReturnData;
import com.yilin.platform.base_core.commons.encrypt.EncryptUtils;
import com.yilin.platform.base_core.commons.utils.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @description:接口加密
 * @date 2022/11/25 14:02
 */
@ControllerAdvice
public class ResResponse<T> implements ResponseBodyAdvice<ReturnData<T>> {
    private ObjectMapper om = new ObjectMapper();

    public ResResponse() {
    }

    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.hasMethodAnnotation(EncryptInterceptor.class);
    }

    @Override
    public ReturnData<T> beforeBodyWrite(ReturnData<T> data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        if (!data.getIsEncrypt()) return data;
        String token = request.getHeaders().getFirst("token");
        if (token==null || UserUtil.getLoginUser(token) == null) {
            String json = JsonUtil.objectToJson(data.getData());
            data.setEncData(EncryptUtils.aesEncrypt(json, null));
            return data;
        }
        String json = JsonUtil.objectToJson(data.getData());
        String aesEncrypt = EncryptUtils.aesEncrypt(json, token);
        data.setEncData(aesEncrypt);
        data.setData(null);
        return data;
    }


}
